package com.lulin.mall.auth.server.controller;

import com.alibaba.fastjson.JSON;
import com.lulin.common.constant.AuthConstant;
import com.lulin.common.constant.SMSConstant;
import com.lulin.common.exception.BizCodEnum;
import com.lulin.common.utils.R;
import com.lulin.common.vo.MemberVo;
import com.lulin.mall.auth.server.fegin.MemberFeignService;
import com.lulin.mall.auth.server.fegin.ThirdPartFeginService;
import com.lulin.mall.auth.server.vo.LoginVo;
import com.lulin.mall.auth.server.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录和注册
 *
 * @author lulin
 * @date 2022/12/6 9:10
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeginService thirdPartFeginService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 根据接收前端注册页面的手机号，远程调用短信服务生成验证码
     *
     * @param phone 手机号
     */
    @ResponseBody
    @GetMapping("/sms/sendSmsCode")
    public R sendSmsCode(@RequestParam("phone") String phone) {
        //防止60s内重复发送
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if (redisCode != null) {
            String s = redisCode.toString();
            if (!"".equals(s)) {
                long time = Long.parseLong(redisCode.toString().split("_")[1]);
                if (System.currentTimeMillis() - time <= 60000) {
                    //说明验证码的发送间隔 不足一分钟 提示
                    return R.error(BizCodEnum.VALID_SMS_EXCEPTION.getCode(), BizCodEnum.VALID_SMS_EXCEPTION.getMsg());
                }
            }
        }
        //生成验证码 (效率高)
        //String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartFeginService.sendSmsCode(phone, code);
        code = code + "_" + System.currentTimeMillis();
        //把验证码 保存到 redis服务中 过期时间5分钟。格式：sms:code: 17809516922   12345
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX + phone, code, 10, TimeUnit.MINUTES);
        return R.ok();
    }

    /**
     * 用户注册
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model) {
        HashMap<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            // 表示提交的数据不合法  提取不合法的  做响应
            List<FieldError> fieldErrors = result.getFieldErrors();
            //获取到了每个字段的对应的错误信息
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field, defaultMessage);
            }
            model.addAttribute("error", map);
            return "/reg";
        } else {
            //验证码是否正确
            String code = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            System.out.println("code获取 = " + code);
            code = code.split("_")[0];
            //如果redis获取的验证码 ！= 生产的验证码
            if (!code.equals(vo.getCode())) {
                //说明验证码不正确
                map.put("code", "验证码不正确");
                model.addAttribute("error", map);
                return "/reg";
            } else {
                //说明验证码正确 ，删除redis中的验证码
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                //远程调用对应的服务，完成注册功能
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    //注册成功，重定向到登录页面
                    return "redirect:http://auth.lulin.com/login.html";
                } else {
                    //注册失败
                    map.put("msg", r.getCode() + ":" + r.get("msg"));
                    model.addAttribute("error", map);
                    return "/reg";
                }
            }
        }
        //return "redirect:/login.html";
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        //用户信息在会员中心，需要远程
        R r = memberFeignService.login(loginVo);
        if (r.getCode() == 0) {
            String entityJson = (String) r.get("entity");
            MemberVo memberVo = JSON.parseObject(entityJson, MemberVo.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS, memberVo);
            //表示登录成功
            return "redirect:http://mall.lulin.com/home";
        }

        redirectAttributes.addAttribute("errors", r.get("msg"));

        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.lulin.com/login.html";
    }
}
